package com.wy.service.impl;

import com.sun.mail.util.MailSSLSocketFactory;
import com.wy.service.EmailService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * description EmailServiceImpl
 * author wy
 * date 2021-09-28 22:20
 **/
@Service(timeout = 30000)
public class EmailServiceImpl implements EmailService
{
    @Value("${email.from.user}")
    private String from;// 发件人的邮箱地址
    @Value("${email.from.password}")
    private String password;// 发件人邮箱客户端的授权码

    @Override
    public boolean sendCode(String to, String text)
    {
        Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");


        try
        {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);

            Session session = Session.getInstance(props);

            Message msg = new MimeMessage(session);
            msg.setSubject("测试邮件");
            msg.setText(text);
            msg.setFrom(new InternetAddress(from));

            Transport transport = session.getTransport();

            transport.connect("smtp.qq.com", from, password);
            transport.sendMessage(msg, new Address[] {new InternetAddress(to) });
            transport.close();
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
            return false;
        }

        return true;
    }
}
